
import java.awt.*;
import java.awt.event.*;
import java.io.IOException;
import java.net.MalformedURLException;
import javax.swing.*;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.omg.CORBA.ORB;
import org.omg.CosNaming.*;



public class CustomerClient extends JFrame implements ActionListener, ListSelectionListener {
	
	static BoxOfficeServer_interface remote_objImpl = null;
	private NamingContextExt ncRef;
	
	//private BoxOfficeServer_Interface remote_obj = null;
	private String locations[] = {"Montreal", "Toronto", "Calgary", "Ottawa", "Vancouver"};
	
	private JLabel Welcomelabel,locationlabel,showlabel,numberOfTickets,customerIDlabel,statuslabel;
	private JButton check,reserve,cancel,exit,exchange;
	private JTextField showEntry,TicketsNumber,customerID;
	private JTextArea statusTextArea;
	private JScrollPane userScrollPane_1,userScrollPane_2;	
	private JList  userList_1;
	private JPanel userPanel_1,userPanel_2;
		
	public CustomerClient() {
		Initialize_GUI();
	}
	
	private void Initialize_GUI(){
		
		setLayout(new BorderLayout());
		
		Welcomelabel = new JLabel("Welcome to DTRS for Shows",JLabel.CENTER);
		Welcomelabel.setFont(new Font("Bitstream Charter",1,40));
		
		userPanel_1 = new JPanel(new FlowLayout(0,15,10));
		
		userList_1 = new JList(locations);
		userList_1.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
		userList_1.setLayoutOrientation(JList.HORIZONTAL_WRAP);
		userList_1.setVisibleRowCount(-1);
		
		userList_1.addListSelectionListener(this);
		
		userScrollPane_1 = new JScrollPane(userList_1);
		userScrollPane_1.setPreferredSize(new Dimension(100, 80));
		locationlabel = new JLabel("1) Select a location:");
		showlabel = new JLabel("                  2) Specify a show:");
		
		showEntry = new JTextField(3);
	
		customerIDlabel = new JLabel("3) Customer ID:");
		customerID = new JTextField(6);
		customerID.setForeground(Color.GRAY);
		
		numberOfTickets = new JLabel("      4) Number Of Tickets:");
		
		TicketsNumber = new JTextField(3);
		check = new JButton("Check");
		check.addActionListener(this);
		
		statuslabel = new JLabel("Status");
		statusTextArea = new JTextArea(8,45);
		statusTextArea.setBorder(BorderFactory.createLineBorder(Color.GRAY));
		statusTextArea.setFont(new Font("Bitstream Charter",1,16));
		userScrollPane_2 = new JScrollPane(statusTextArea,JScrollPane.VERTICAL_SCROLLBAR_ALWAYS,JScrollPane.HORIZONTAL_SCROLLBAR_NEVER);
		
		userPanel_2 = new JPanel(new FlowLayout(1,30,30));
		
		reserve = new JButton("Reserve/Submit");
		reserve.addActionListener(this);
		
		cancel = new JButton("Cancel Reservation");
		cancel.addActionListener(this);
		exit = new JButton("Exit");
		exit.addActionListener(this);
		exchange = new JButton("Exchange");
		exchange.addActionListener(this);
		
		userPanel_1.add(userScrollPane_1,FlowLayout.LEFT);
		userPanel_1.add(locationlabel,FlowLayout.LEFT);
		userPanel_1.add(check);
		userPanel_1.add(statuslabel);
		userPanel_1.add(userScrollPane_2);
		userPanel_1.add(check,FlowLayout.RIGHT);
		userPanel_1.add(showEntry,FlowLayout.RIGHT);
		userPanel_1.add(showlabel,FlowLayout.RIGHT);
		userPanel_1.add(customerIDlabel);
		userPanel_1.add(customerID);
		userPanel_1.add(numberOfTickets);
		userPanel_1.add(TicketsNumber);
		
		userPanel_2.add(reserve);
		userPanel_2.add(cancel);
		userPanel_2.add(exchange);
		userPanel_2.add(exit);
		
		getContentPane().add(Welcomelabel, BorderLayout.NORTH);
		getContentPane().add(userPanel_1, BorderLayout.CENTER);
		getContentPane().add(userPanel_2, BorderLayout.SOUTH);
		
		pack();
		setSize(700,500);
		setResizable(false);
		setDefaultCloseOperation(EXIT_ON_CLOSE);
		
		
	}
	
	protected void setUpConnection(String args[]){
		try{
			ORB orb = ORB.init(args, null);
			org.omg.CORBA.Object objRef = 
			orb.resolve_initial_references("NameService");
			
			ncRef = 
			NamingContextExtHelper.narrow(objRef);
			
			//helloImpl = 
			//HelloHelper.narrow(ncRef.resolve_str("Hello"));
			//String result = helloImpl.sayHello();
			
			/*remote_objImpl=
			BoxOfficeServer_interfaceHelper.narrow(ncRef.resolve_str("BoxOfficeServer_montreal"));*/	
			
			System.out.println("Until now everything is OK.");
		//	helloImpl.shutdown();
			
		}
		catch(Exception exc){
			System.out.println("Error while setting up a connection!");
		}
		
	}
	
	@Override
	public void valueChanged(ListSelectionEvent e) {
		
		if(e.getSource().equals(userList_1)){
			
			int index = userList_1.getSelectedIndex();
			
			try{
				
				/* Five BoxOfficeServers {montreal, toronto, calgary, ottawa, vancouver} */	
				switch(index){
				case (0): 
					System.out.println("Index " + index);
					/* Server IP address 192.168.1.106 */
					remote_objImpl=
					BoxOfficeServer_interfaceHelper.narrow(ncRef.resolve_str("montreal"));	
					
				break;
				
				case (1): 
					System.out.println("Index " + index);
					remote_objImpl=
					BoxOfficeServer_interfaceHelper.narrow(ncRef.resolve_str("toronto"));		
				break;
				
				case (2): 
					System.out.println("Index " + index);
					remote_objImpl=
					BoxOfficeServer_interfaceHelper.narrow(ncRef.resolve_str("calgary"));
				break;
				
				case (3): 
					System.out.println("Index " + index);
					remote_objImpl=
					BoxOfficeServer_interfaceHelper.narrow(ncRef.resolve_str("ottawa"));
				break;
				
				case (4):
					System.out.println("Index " + index);
					remote_objImpl=
						BoxOfficeServer_interfaceHelper.narrow(ncRef.resolve_str("vancouver"));
				break;
				
				default: System.out.println("Invalid");
				break;
				
				}
				
			} catch (Exception exc) {
				
				exc.printStackTrace();
			} 
			
		}
		
	}
	
	@Override
	public void actionPerformed(ActionEvent evt){
		
		if(evt.getSource().equals(check)){
			
			statusTextArea.setText("");
			statusTextArea.append("Loading..\nPlease wait..\n\n");
			
			//int status;
			int status = 0;
			String requiredShow;
			
			try {
				
				requiredShow = showEntry.getText();
				
				/* first of all make sure the user enter a valid-formatted show number  */
				if(requiredShow.length() == 3){
					
					//status = remote_obj.check(requiredShow);
					status = remote_objImpl.check(requiredShow);
					if(status != -1){
						statusTextArea.append("Available tickets for show " + requiredShow + " : " + status + "\n");
					}
					else statusTextArea.append("Invalid show ID, try another ID..\n");
					
				}
				else{
					statusTextArea.append("Invalid show ID, try another ID..\n");
					}
			} catch (Exception excCheck) {//RemoteEx
				
				statusTextArea.append(excCheck.getMessage());
			}
			
		}
		
		else if(evt.getSource().equals(reserve) || evt.getSource().equals(cancel)){
			
			try{
				String ID_string = customerID.getText();
				String showID_string = showEntry.getText();
				
				/* make sure user-data is in a correct form before making any remote invocation */
				if(ID_string.length() == 6 && showID_string.length() == 3){
					
					int ID = Integer.parseInt(customerID.getText());
					showID_string = showEntry.getText();
					int numberOfTickets = Integer.parseInt(TicketsNumber.getText());
					
					try{
						if(evt.getSource().equals(reserve) && numberOfTickets != 0){
							
							String reply = remote_objImpl.reserve(ID, showID_string, numberOfTickets);
							
							if(reply.equals("Approved."))
							statusTextArea.append("\n" + reply + " You've got " + numberOfTickets + " tickets for the show " + showID_string + ".\n");
							
							else statusTextArea.append(reply + "\n"); 
							
						}
						else if(evt.getSource().equals(cancel)){ 
					
							String reply = remote_objImpl.cancel(ID, showID_string, numberOfTickets);
							statusTextArea.append("\n" + reply);
							
						}
						
					}
					catch(Exception remoteExc){//RemoteExc
						statusTextArea.append(remoteExc.getMessage());
					}
					
				}
				else statusTextArea.append("\nInvalid infos!, please make sure again..\n");
				
			}
			catch(Exception IOexc){
				statusTextArea.append("Invalid Informations!\n" + IOexc.getMessage());
			}
		}
		
		else if(evt.getSource().equals(exchange)){
			new ExchangeWindow();
			
		}
		else {
			/* if user clicked on Exit button */
			System.exit(0);
		}
		
	}
	
	class ExchangeWindow extends JFrame implements ActionListener, ListSelectionListener{
		
		private JLabel customerIDlabel, reservedShowlabel, reservedTicketslabel, desiredShowlabel, 
					   desiredShowLoclabel, desiredTicketslabel, label1, label2, statuslabel; 
		private JButton exchange,cancel;
		private JTextField customerID,reservedShow,reservedTickets, desiredShow, 
		   				   desiredShowLoc, desiredTickets;
		
		private JList prefixList;
		private JScrollPane prefixPane;
		
		private String prefix = "";
		
		public ExchangeWindow() {
			
			setLayout(new FlowLayout(FlowLayout.CENTER,5,10));
			
			prefixList = new JList(locations);
			prefixList.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
			prefixList.setLayoutOrientation(JList.HORIZONTAL_WRAP);
			prefixList.setVisibleRowCount(-1);
			
			prefixList.addListSelectionListener(this);
			
			prefixPane = new JScrollPane(prefixList);
			prefixPane.setPreferredSize(new Dimension(100, 80));
			
			label1 = new JLabel("__________________________________________" +
								"__________________________________________");
			
			customerIDlabel = new JLabel("Customer ID: ");
			customerID = new JTextField(6);
			
			reservedShowlabel = new JLabel("reserved show: ");
			reservedShow = new JTextField(3);
			
			reservedTicketslabel = new JLabel("reserved tickets: ");
			reservedTickets = new JTextField(3);
			
			desiredShowlabel = new JLabel("desired show: ");
			desiredShow = new JTextField(3);
			
			desiredTicketslabel = new JLabel("desired tickets: ");
			desiredTickets = new JTextField(3);
			desiredShowLoclabel = new JLabel("show location: ");
			
			label2 =  new JLabel("__________________________________________" +
								 "__________________________________________");
			
			statuslabel = new JLabel("statusssssssssssssssssssssssss");
			
			exchange = new JButton("Exchange");
			cancel = new JButton("cancel");
			
			add(customerIDlabel);
			add(customerID);
			add(reservedShowlabel);
			add(reservedShow);
			add(reservedTicketslabel);
			add(reservedTickets);
			add(label1);
			add(desiredShowlabel);
			add(desiredShow);
			add(desiredTicketslabel);
			add(desiredTickets);
			add(desiredShowLoclabel);
			add(prefixPane);
			add(label2);
			add(exchange);
			add(cancel);
			
			exchange.addActionListener(this);
			cancel.addActionListener(this);
			
			setTitle("Exchange Operation");
			setLocationRelativeTo(null);
			setSize(550,250);
			setLocation(200,200);
			setResizable(false);
			setFocusable(true);
			setVisible(true);
			
			
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			if(e.getSource().equals(exchange)){
				
				try{
					String customer_string = customerID.getText();
					String showID_reserve = reservedShow.getText();
					String showID_desire = desiredShow.getText();
					String tickets_reserve = reservedTickets.getText();
					String tickets_desire = desiredTickets.getText();
					
					/* make sure user-data is in a correct form before making any remote invocation */
					if(customer_string.length() == 6 && showID_reserve.length() == 3 
					   && showID_desire.length() == 3){
						
						if (Integer.parseInt(tickets_reserve) <= Integer.parseInt(tickets_desire)){
					
							System.out.println("Correct information.");
						
							remote_objImpl=
								BoxOfficeServer_interfaceHelper.narrow(ncRef.resolve_str("montreal"));	
		
							String reply = remote_objImpl.exchange(Integer.parseInt(customer_string)
									, showID_reserve, prefix, Integer.parseInt(tickets_reserve),
									showID_desire, Integer.parseInt(tickets_desire));
							
							statusTextArea.setText("");
							statusTextArea.append("Your Exchange: " + reply + "\n\nthank you for choosing us!");
							dispose();
							
						}
						else{
							statusTextArea.setText("");
							statusTextArea.append("Sorry, Desired tickets must be more/equal to reserved tickets!");
							dispose();
						}
						
					
					
					}
					else {
						statusTextArea.setText("");
						statusTextArea.append("Invalid information!");
						dispose();
					}
				}
				catch(Exception exc){
					statusTextArea.setText("");
					statusTextArea.append("Invalid information!");
					dispose();
				}
				
			}	
			
			else{
				dispose();
			}
			
		}

		@Override
		public void valueChanged(ListSelectionEvent e) {
			
			if(e.getSource().equals(prefixList)){
				
				int index = prefixList.getSelectedIndex();
				try{
					switch(index){
					case (0): 
						System.out.println("prefix " + index);
						prefix = "MONTREAL";
					break;
					
					case (1): 
						System.out.println("prefix " + index);
						prefix = "TORONTO";
					break;
					
					case (2): 
						System.out.println("prefix " + index);
						prefix = "CALGARY";
					break;
					
					case (3): 
						System.out.println("prefix " + index);
						prefix = "OTTAWA";
					break;
					
					case (4):
						System.out.println("prefix " + index);
						prefix = "VANCOUVER";
					break;
					
					default: 
						System.out.println("Invalid");
						prefix = "NOVALUE";
					break;
					
					}
					
				} catch (Exception exc) {
					
					exc.printStackTrace();
				} 
				
			}
			
		}
		
	}
	
	public static void main(final String args[]){
		SwingUtilities.invokeLater(new Runnable() {
			public void run() {
			CustomerClient client = new CustomerClient();
			client.setTitle("Customer");
			client.setLocationRelativeTo(null);
			client.setLocation(100,100);
			client.setUpConnection(args);
			client.setVisible(true);
				
			}
		});
	}


}
